/**
 * Copyright (C) 2009 Matteo Merli <mm@merlimat.org>
 * 
 * $Id: PxlString.java 22 2009-01-12 22:10:50Z matteo.merli $
 * $URL: http://pxl-lang.googlecode.com/svn/trunk/src/main/java/pxl/types/PxlString.java $
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *         http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package pxl.types;

import java.util.Map;
import java.util.Collection;

import pxl.errors.IndexError;
import pxl.errors.InvalidComparison;
import pxl.errors.TypeError;
import pxl.errors.UnsupportedOperand;
import pxl.types.annotations.Exported;

/**
 * @author Matteo Merli
 */
public final class PxlString extends PxlObject implements Comparable<PxlString>
{

    protected static final PxlString EmptyString = new PxlString( "" );

    private final String value;

    public PxlString( String value )
    {
        this.value = value;
    }

    public static PxlString parse(String str)
    {
        char quoteChar = str.charAt( 0 );
        int start = 0;
        int end;

        boolean raw = false;
        if ( quoteChar == 'r' || quoteChar == 'R' )
        {
            raw = true;
            start++;
        }

        int quotes = 3;
        if ( str.length() - start == 2 )
            quotes = 1;
        if ( str.charAt( start ) != str.charAt( start + 1 ) )
            quotes = 1;

        start += quotes;
        end = str.length() - quotes;

        str = str.substring( start, end );
        return new PxlString( str );
    }

    @Override
    public String getType()
    {
        return "String";
    }

    @Override
    public String toString()
    {
        return value;
    }

    public String getValue()
    {
        return value;
    }

    // // Operators

    @Exported
    @Override
    public PxlString __str__()
    {
        return this;
    }

    @Exported
    @Override
    public PxlString __repr__()
    {
        StringBuilder sb = new StringBuilder( value.length() + 2 );
        sb.append( "'" ).append( value ).append( "'" );
        return new PxlString( sb.toString() );
    }

    @Exported
    @Override
    public PxlObject __add__(PxlObject other)
    {
        if ( !(other instanceof PxlString) )
        {
            throw new UnsupportedOperand( "+", this, other );
        }

        // Concatenate 2 strings
        return new PxlString( value + ((PxlString) other).value );
    }

    @Exported
    @Override
    public PxlObject __mul__(PxlObject other)
    {

        if ( other instanceof PxlInteger )
        {
            // "hello" * 3 ===> "hellohellohello"

            long n = ((PxlInteger) other).getValue();
            StringBuilder sb = new StringBuilder( (int) (value.length() * n) );
            for ( long i = 0; i < n; i++ )
                sb.append( value );

            return new PxlString( sb.toString() );
        }

        throw new UnsupportedOperand( "*", this, other );
    }

    @Exported
    @Override
    public PxlBoolean __bool__()
    {
        return PxlBoolean.valueOf( value.length() != 0 );
    }

    // Comparison

    @Exported
    @Override
    public PxlBoolean __eq__(PxlObject other)
    {
        if ( !(other instanceof PxlString) )
            return PxlBoolean.False;
        String otherValue = ((PxlString) other).value;
        return PxlBoolean.valueOf( value.equals( otherValue ) );
    }

    @Exported
    @Override
    public PxlBoolean __neq__(PxlObject other)
    {
        if ( !(other instanceof PxlString) )
            return PxlBoolean.True;
        String otherValue = ((PxlString) other).value;
        return PxlBoolean.valueOf( !value.equals( otherValue ) );
    }

    @Exported
    @Override
    public PxlBoolean __lt__(PxlObject other)
    {
        if ( !(other instanceof PxlString) )
            throw new InvalidComparison( this, other );
        int res = value.compareTo( ((PxlString) other).value );
        return PxlBoolean.valueOf( res < 0 );
    }

    @Exported
    @Override
    public PxlBoolean __lte__(PxlObject other)
    {
        if ( !(other instanceof PxlString) )
            throw new InvalidComparison( this, other );
        int res = value.compareTo( ((PxlString) other).value );
        return PxlBoolean.valueOf( res <= 0 );
    }

    @Exported
    @Override
    public PxlBoolean __gt__(PxlObject other)
    {
        if ( !(other instanceof PxlString) )
            throw new InvalidComparison( this, other );
        int res = value.compareTo( ((PxlString) other).value );
        return PxlBoolean.valueOf( res > 0 );
    }

    @Exported
    @Override
    public PxlBoolean __gte__(PxlObject other)
    {
        if ( !(other instanceof PxlString) )
            throw new InvalidComparison( this, other );
        int res = value.compareTo( ((PxlString) other).value );
        return PxlBoolean.valueOf( res >= 0 );
    }

    @Override
    public int hashCode()
    {
        return value.hashCode();
    }

    @Override
    public boolean equals(Object other)
    {
        if ( other instanceof PxlString )
        {
            return value.equals( ((PxlString) other).value );
        }
        else if (other instanceof String)
            return value.equals( other );
        return false;
    }

    @Exported
    @Override
    public PxlObject __getitem__(PxlObject key)
    {
        if ( !(key instanceof PxlInteger) )
            throw new TypeError( "char indices must be integers" );

        int idx = (int) ((PxlInteger) key).getValue();
        if ( idx >= value.length() )
            throw new IndexError( "list index out of range" );

        return new PxlString( Character.toString( value.charAt( idx ) ) );
    }

    @Exported
    @Override
    public void __setitem__(PxlObject key, PxlObject value)
    {
        if ( !(key instanceof PxlInteger) )
            throw new TypeError( "list indices  must be integers" );

        // int idx = (int) ((PxlInteger) key).getValue();
        // if (idx >= list.size())
        throw new IndexError( "list assignment index out of range" );

        // list.set(idx, value);
    }

    @Exported
    @Override
    public PxlIterator __getiterator__()
    {
        return new PxlStringIterator( value );
    }

    @Exported
    @Override
    public PxlInteger __len__()
    {
        return new PxlInteger( value.length() );
    }

    // Public methods

    @Exported
    public PxlString lower()
    {
        return new PxlString( value.toLowerCase() );
    }

    @Exported
    public PxlString upper()
    {
        return new PxlString( value.toUpperCase() );
    }

    // /////////////////

    public int compareTo(PxlString other)
    {
        return value.compareTo( other.value );
    }

    public static class PxlStringIterator extends PxlIterator
    {
        private final String value;
        private int idx;

        public PxlStringIterator( String value )
        {
            this.value = value;
            idx = 0;
        }

        @Override
        public PxlBoolean hasNext()
        {
            return PxlBoolean.valueOf( idx < value.length() );
        }

        @Override
        public PxlObject next()
        {
            if ( idx >= value.length() )
                throw new IteratorException(
                        "There aren't elements left in the iterator." );

            return new PxlString( Character.toString( value.charAt( idx++ ) ) );
        }

        @Override
        public void remove()
        {
        }

    }

    // Attributes

    private static final Map<String, PxlObject> attrs = PxlObject
            .getExportedMethods( PxlString.class );

    @Override
    protected PxlObject getAttribute(String name)
    {
        return attrs.get( name );
    }

    @Override
    protected Collection<String> getAttributeNames()
    {
        return attrs.keySet();
    }

    // ////////////////////////////////////////////////////////////////////////

}
